package cn.com.se.sharepictrue.business;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.util.SimpleArrayMap;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.List;

import cn.com.se.sharepictrue.AppContext;
import cn.com.se.sharepictrue.bean.BaseUser;
import cn.com.se.sharepictrue.bean.Comment;
import cn.com.se.sharepictrue.bean.ConcernAndFans;
import cn.com.se.sharepictrue.bean.HomeShareBean;
import cn.com.se.sharepictrue.bean.MineCommentBean;
import cn.com.se.sharepictrue.bean.UserInfoBean;
import cn.com.se.sharepictrue.utils.ToastUtils;
import cz.msebera.android.httpclient.Header;

/**
 * Created by KIDNG on 2015/11/27.
 */
public class ShareApi {

    public static void register(Context context,String userPhone,String password,CallBack<NetworkResponse<String>> callBack){
        RequestParams params = new RequestParams();
        params.put("userPhone",userPhone);
        params.put("password",password);
        post(context,URLS.register,params,callBack);
    }

    public static void modifyPassword(Context context,
                                      String userPhone,
                                      String oldPassword,
                                      String newPassword,
                                      String confirmPassword,
                                      CallBack<NetworkResponse<String>> callBack){
        RequestParams params = new RequestParams();
        params.put("userPhone",userPhone);
        params.put("oldPassword",oldPassword);
        params.put("password1",newPassword);
        params.put("password2",confirmPassword);
        post(context,URLS.modifyPassword,params,callBack);
    }

    public static void BanUserList(Context context,CallBack<NetworkResponse<List<UserInfoBean>>> callBack){
        post(context,URLS.userBanList,new RequestParams(),callBack);
    }

    public static void adminBanUser(Context context, boolean isAllow, String userID, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("isAllow", isAllow ? "0" : "1");
        params.put("userID", userID);
        post(context, URLS.adminBanUser, params, callBack);
    }

    public static void hideMyAllShare(Context context, boolean noShow, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("isShow", noShow ? "0" : "1");
        post(context, URLS.hideMyShare, params, callBack);
    }

    public static void search(Context context, String search, CallBack<NetworkResponse<List<HomeShareBean>>> callBack) {
        RequestParams params = new RequestParams();
        params.put("search", search);
        post(context, URLS.search, params, callBack);
    }

    public static void getShareComment(Context context, String shareId, CallBack<NetworkResponse<List<Comment>>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareId);
        post(context, URLS.shareAllComment, params, callBack);
    }

    public static void getPraiseRank(Context context, int type,int page, CallBack<NetworkResponse<List<HomeShareBean>>> callBack) {
        RequestParams params = new RequestParams();
        params.put("order", type);
        params.put("p", page);
        post(context, URLS.rank, params, callBack);
    }

    public static void getHomeList(Context context, int whatPage, CallBack<NetworkResponse<List<HomeShareBean>>> callBack) {
        SimpleArrayMap<String, String> params = new SimpleArrayMap<>();
        params.put("p", "" + whatPage);
        get(context, URLS.homeShare, params, callBack);
    }

    public static void praise(Context context, String shareId, int likeIt, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareId);
        params.put("likeIt", "" + likeIt);
        post(context, URLS.praise, params, callBack);
    }

    public static void praise(Context context, String shareId, boolean isLikeIt, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareId);
        params.put("likeIt", isLikeIt ? 1 : 0 + "");
        post(context, URLS.praise, params, callBack);
    }

    public static void concern(Context context, String userId, boolean concernHim, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("userID", userId);
        params.put("concernHim", concernHim ? 1 : 0 + "");
        post(context, URLS.concern, params, callBack);
    }

    public static void favorite(Context context, String shareId, int favorite, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareId);
        params.put("favorite", "" + favorite);
        post(context, URLS.favorite, params, callBack);
    }

    public static void favorite(Context context, String shareId, boolean isFavorite, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareId);
        params.put("favorite", isFavorite ? 1 : 0 + "");
        post(context, URLS.favorite, params, callBack);
    }

    public static void sendComment(Context context, String shareID, String comment, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareID);
        params.put("comment", comment);
        post(context, URLS.comment, params, callBack);
    }

    public static void replyComment(Context context, String shareID, String userID, String commentID, String comment, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("shareID", shareID);
        params.put("userID", userID);
        params.put("commentID", commentID);
        params.put("comment", comment);
        post(context, URLS.replyComment, params, callBack);
    }

    //12/2 kaiyu
    public static void share(Context context, String sayHi, File[] images, CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("sayHi", sayHi);
        try {
            for (int i = 1; i < images.length + 1; i++)
                params.put("photo" + i, images[i - 1]);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        post(context, URLS.share, params, callBack);
    }

    public static void userInfo(Context context, CallBack<NetworkResponse<UserInfoBean>> callBack) {
        post(context, URLS.userInfo, null, callBack);
    }

    public static void modifyUser(Context context, String nickName,
                                  String introduction, String sex, String qq,
                                  String email, String portraitPath,
                                  CallBack<NetworkResponse<String>> callBack) {
        RequestParams params = new RequestParams();
        params.put("userName", nickName);
        if (portraitPath.length() > 2) {
            File file = new File(portraitPath);
            if (file.isFile())
                try {
                    params.put("portrait", file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
        }
        params.put("signature", introduction);
        params.put("gender", sex);
        params.put("qq",qq);
        params.put("userEmail",email);
        post(context, URLS.modifyUser, params, callBack);
    }

    public static void getMyShare(Context context, CallBack<NetworkResponse<List<HomeShareBean>>> callBack) {
        get(context, URLS.myShare, null, callBack);
    }

    /**
     * 获取主页信息
     */
    public static void herShare(Context context, String userId, int page, int pageSize, CallBack<NetworkResponse<List<HomeShareBean>>> callBack) {
        SimpleArrayMap<String, String> params = new SimpleArrayMap<>();
        params.put("userID", userId);
        params.put("p", page + "");
       // params.put("pSize", pageSize + "");
        get(context, URLS.herShare, params, callBack);
    }

    /**
     *获取关注数粉丝数
     */
    public static void getUserConcernAndFans(Context context,String userId,CallBack<NetworkResponse<ConcernAndFans>> callBack)
    {
        RequestParams params = new RequestParams();
        params.put("userID",userId);
        post(context, URLS.otherUserInfo, params, callBack);
    }

    public static void logOut(Context context, CallBack<NetworkResponse<String>> callBack) {
        post(context, URLS.logout, null, callBack);
    }

    /**
     * 获取我的收藏
     */
    public static void getMyCollection(Context context,int page,CallBack<NetworkResponse<List<HomeShareBean>>> callBack)
    {
        SimpleArrayMap<String, String> params = new SimpleArrayMap<>();
        params.put("p", page + "");
        get(context, URLS.myFavorite, params, callBack);
    }

    /**
     * 获取我的点赞
     */
    public static void getMyLike(Context context,int page,CallBack<NetworkResponse<List<HomeShareBean>>> callBack)
    {
        SimpleArrayMap<String, String> params = new SimpleArrayMap<>();
        params.put("p", page + "");
        get(context, URLS.myLike, params, callBack);
    }

    /**
     * 获取我的评论
     */
    public static void getMyComment(Context context,int page,CallBack<NetworkResponse<List<MineCommentBean>>> callBack)
    {
        SimpleArrayMap<String, String> params = new SimpleArrayMap<>();
        params.put("p", page + "");
        get(context, URLS.myComment, params, callBack);
    }

    /**
     * 获取我的粉丝列表
     */
    public static void getMyFansList(Context context, int nowPage, CallBack<NetworkResponse<List<BaseUser>>> callBack) {
        RequestParams params = new RequestParams();
        params.put("p",nowPage);
        post(context, URLS.myFans, params, callBack);
    }

    /**
     * 获取我的关注列表
     */
    public static void getMyConcernList(Context context, int nowPage, CallBack<NetworkResponse<List<BaseUser>>> callBack) {
        RequestParams params = new RequestParams();
        params.put("p",nowPage);
        post(context, URLS.myConcern, params, callBack);
    }

    private static <T> void post(Context context, String url,RequestParams params, final CallBack<T> callBack) {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
        AsyncHttpHelper.getInstance().setCookieStore(myCookieStore);
        callBack.onPreExecute();
        AsyncHttpHelper.getInstance().post(context, url, params, new BaseJsonHttpResponseHandler<T>() {
            @Override
            public void onStart() {
                super.onStart();
                callBack.onStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, T response) {
                callBack.onSuccess(response);
                Log.d("test", response.toString());
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, T errorResponse) {
                callBack.onFailure();
                if (rawJsonData != null)
                    Log.d("test", rawJsonData);
            }

            @Override
            protected T parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                if (isFailure)
                    return null;
                else
                    return AppContext.getGson().fromJson(rawJsonData, callBack.type);
            }
        });
        Log.d("test", url);
    }

    private static <T> void get(Context context, final String url, @Nullable SimpleArrayMap<String, String> params, final CallBack<T> callBack) {
        StringBuffer sb = new StringBuffer(url);
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                String key = params.keyAt(i);
                String values = params.get(key);
                if (i == 0) sb.append("?");
                else sb.append("&");
                sb.append(key);
                sb.append("=");
                sb.append(values);
            }
        }
        PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
        AsyncHttpHelper.getInstance().setCookieStore(myCookieStore);
        callBack.onPreExecute();
        AsyncHttpHelper.getInstance().get(context, sb.toString(), new BaseJsonHttpResponseHandler<T>() {
            @Override
            public void onStart() {
                super.onStart();
                callBack.onStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, T response) {
                callBack.onSuccess(response);
                Log.d("test", response.toString());
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, T errorResponse) {
                callBack.onFailure();
                Log.d("test", rawJsonData);
            }

            @Override
            protected T parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                if (isFailure)
                    return null;
                else
                    return AppContext.getGson().fromJson(rawJsonData, callBack.type);
            }
        });
        Log.d("test", url);

    }

    private ShareApi() {
    }
}
